package logic;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JTextArea;
import org.apache.commons.lang.StringUtils;

/**
 * 工具类
 * @author 骆焕
 *
 */
public class Utils {
	
	/** 
	* @des: 十六进制字符串转为字节数组 
	* @param: [hex] 
	* @return:
	* @date: 2020-06-09 
	*/
	public static byte[] hexStringToBytes(String hex){
		hex = hex.replaceAll(" ", "");
		if(hex.length() % 2 != 0) return null;
		int len =  (int)Math.ceil(hex.length() / 2);
		byte[] bytes = new byte[len];
		int index = 0;
		for(int i=0; i< hex.length(); i += 2){
			bytes[index++] = (byte)(Short.valueOf(hex.substring(i, i + 2), 16) & 0xFF);
		}
		return bytes;
	}
	
	/** 
	* @des: 字节数组转为十六进制字符串 
	* @param: [buf] 
	* @return: 
	* @date: 2020-06-09 
	*/
	public static String bytesToHexString(byte[] bytes){
		if(bytes == null || bytes.length == 0) return "";
		StringBuilder strHex = new StringBuilder();
		int len = bytes.length;
		for(int i = 0; i < len; i++){
			strHex.append(StringUtils.leftPad(Integer.toHexString(bytes[i] & 0xFF).toUpperCase(), 2, "0"));
		}
		return strHex.toString();
	}
	
    /**
     * 获取当前时间
     * @return
     */
	private static String getCurrentTime() {
    	Calendar calendar= Calendar.getInstance();
    	SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
    	return dateFormat.format(calendar.getTime());
    }
    
	/**
	 * 在文本框中记录消息
	 * @param sendArea
	 * @param message
	 */
    public static void recordMsg(JTextArea sendArea, String message) {
    	String recordMsg = getCurrentTime() + ": " + message;
    	String lineSeparator = System.lineSeparator();
    	
    	String oldMessage = sendArea.getText();
    	String[] textRows = sendArea.getText().split(lineSeparator);
    	if (textRows.length >= ConfigInfo.getInstance().jTextRows) {
    		oldMessage = oldMessage.substring(0, oldMessage.lastIndexOf(lineSeparator) - 1);
    	}
    	sendArea.setText(recordMsg + lineSeparator + oldMessage);
    	
    	// 不清除式追加日志
    	// sendArea.append(recordMsg);
    }
}
